package cn.mesmile.juc.completable;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author zb
 * @date 2021/8/18 15:11
 * @Description 异步任务
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 【没有返回值】
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException("这里抛出异常,外部[不会]捕获到异常");
            }
            // 这里发生异常，外部会捕获到并中断程序
            int a = 1/0;
            System.out.println(Thread.currentThread().getName() + "【没有】返回值的参数");
        });
        System.out.println("111111111111111111111111");
        // 异步任务完成后会执行这里
//        voidCompletableFuture.get();
        voidCompletableFuture.whenComplete((value,throwable) ->{
            System.out.println("value = " + value);
            System.out.println("throwable = " + throwable);
        }).get();
        // 异步任务发生异常，后面都不会执行
        System.out.println("222222222222222222222222");

        // --------------------------------------------------------------------------------

        // 【拥有返回值】
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() ->{
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("这里抛出异常,外部[不会]捕获到异常");
            }
            // 这里发生异常，外部会捕获到并中断程序
            int a = 1/0;
            System.out.println(Thread.currentThread().getName() + "【有】返回值的参数");
            return 100;
        });

        completableFuture.whenComplete((value,throwable)->{
            System.out.println(" completableFuture value = " + value);
            System.out.println(" completableFuture throwable = " + throwable);
        }).get();
        // 异步任务发生异常，后面都不会执行
        System.out.println("33333333333333333333333333333333333");
    }
}
